package com.jy.rhin.utils;

import com.jy.common.X509TrustUtil;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class FileUtil {
    public static InputStream getInputStream(String aliNetwork) throws Exception {
//        String PATTERNIP = "(\\d*\\.){3}\\d*";
        String PATTERNIP = "^http://[^\\s/$.?#].[^\\s]*$";
        Pattern ipPattern = Pattern.compile(PATTERNIP);
        Matcher matcher = ipPattern.matcher(aliNetwork);
        boolean isHttp = matcher.find();
//        aliNetwork = String.format(isHttp ? "http://%s" : "https://%s", aliNetwork);
        log.info("访问的地址：{}", aliNetwork);
        SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
        sslcontext.init(null, new TrustManager[]{new X509TrustUtil()}, new java.security.SecureRandom());
        URL url = new URL(aliNetwork);
        HostnameVerifier ignoreHostnameVerifier = (s, sslSession) -> {
            log.warn("WARNING: Hostname is not matched for cert.");
            return true;
        };

        InputStream in;
        if (isHttp) {
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setConnectTimeout(6000);
            urlCon.setReadTimeout(6000);
            int code = urlCon.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                log.info("文件读取失败，错误原因为: {}", urlCon.getResponseMessage());
                throw new IOException("文件读取失败");
            }
            in = urlCon.getInputStream();
        } else {
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();
            urlCon.setConnectTimeout(6000);
            urlCon.setReadTimeout(6000);
            int code = urlCon.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                log.info("文件读取失败，URL为: {}，错误原因为: {}", aliNetwork, urlCon.getResponseMessage());
                throw new IOException("文件读取失败");
            }
            in = urlCon.getInputStream();
        }
        return in;
    }
}
